<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of insertSurat
 *
 * @author brlnt
 */
class Surat extends CI_Controller {

    public function Surat() {
        parent::__construct();
		if(!$this->session->userdata('islogin')) redirect('auth');
        $this->load->model('surat_model');
		$this->load->model('log_model');
    }

    public function index() {
		$data['title'] = 'Form Upload Surat';
		$data['kategori_parent']= $this->kategori_array(0);
        $this->load->view('insert_surat_view', $data);
    }

	private function kategori_array($id){
		$query = $this->surat_model->getCategoriesByParent($id);
		$arraydata = array();
		if ($query->num_rows() > 0) {
			foreach($query->result() as $row) {
				$hasilquery = array(
					'id' => $row->idkategori,
					'nama' => $row->nama_kategori
				);
				array_push($arraydata, $hasilquery);
			}
		} else{
			$hasilquery = array(
				'id' => "-2",
				'nama' => "Tidak ada data"
			);
			array_push($arraydata, $hasilquery);
		}
		return $arraydata;
	}
	
    public function insert() {
		// field upload file name in form = file
		$filepath = 'file';
		
        //upload confg
        $config['upload_path'] = './uploads/';
        $config['max_size'] = '0';
        $config['allowed_types'] = '*';
		
		//renaming file
		$filename = $_FILES[$filepath]['name'];
		$ext = pathinfo($filename, PATHINFO_EXTENSION);
		$this->load->helper('date');
		$config['file_name'] = now()."_".$this->input->post('kategori')."_".$this->input->post('kode-surat')."_".$this->input->post('nomer-surat').".".$ext;
		
		// load library with configuration
		$this->load->library('upload', $config);
		
        if (!$this->upload->do_upload($filepath) == TRUE) {
            $error['title'] = 'Error, Please select a file';
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('error', $error);
        } else {
            //get data from form
            $data['nomersurat'] = $this->input->post('nomer-surat');
            $data['nama_instansi'] = $this->input->post('nama-instansi');
            $data['tanggal_kerjasama'] = $this->input->post('tanggal-kerjasama');
            $data['masa_berlaku'] = $this->input->post('masa-berlaku');
            $data['kerjasama_mengenai'] = $this->input->post('kerjasama');
            $data['kode_surat'] = $this->input->post('kode-surat');
            $data['deskripsi'] = $this->input->post('deskripsi');
            $data['unit_terkait'] = $this->input->post('unit-terkait');
            $data['implementasi'] = $this->input->post('implementasi');
            $data['kategori_idkategori'] = $this->input->post('kategori');
            $data['loginuser_idloginuser'] = $this->session->userdata('id');
			
            $upload_data = $this->upload->data('file_name');
            $data['scan_file'] = $upload_data['file_name'];
            $id_entitas = $this->surat_model->insert_surat($data);
			
			$logdata['id_user'] = $this->session->userdata('id');
			$logdata['id_entitas'] = $id_entitas;
			$logdata['nama_tabel'] = 'surat';
			$logdata['action'] = 'insert';
			$this->log_model->setLogData($logdata);
            redirect('surat');
        }
    }

    public function category($cat) {
    	// query berdasarkan category
        $query = $this->surat_model->getSuratByCategory($cat);
        $data['breadcrumb'] = $this->surat_model->getCategories($cat);

        // load library & konfigurasi pagination
        $this->load->library('pagination');
        $config['base_url'] = site_url().'/surat/category/'.$cat.'/';
        $config['total_rows'] = $query->num_rows();
        $config['per_page'] = '1';
        $config['first_page'] = 'Awal'; 
		$config['last_page'] = 'Akhir'; 
		$config['next_page'] = '&laquo;'; 
		$config['prev_page'] = '&raquo;';
		$config['uri_segment'] = 4;
		//styling pagination
		$config['full_tag_open'] = '<ul class="pagination">';
		$config['full_tag_close'] = '</ul>';
		$config['first_tag_open'] = '<li>';
		$config['first_tag_close'] = '</li>';
		$config['last_tag_open'] = '<li>';
		$config['last_tag_close'] = '</li>';
		$config['next_tag_open'] = '<li>';
		$config['next_tag_close'] = '</li>';
		$config['prev_tag_open'] = '<li>';
		$config['prev_tag_close'] = '</li>';
		$config['cur_tag_open'] = '<li class="active"><span>';
		$config['cur_tag_close'] = '<span class="sr-only">(current)</span></span></li>';
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';

		$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
        //initiation
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();

        if ($query->num_rows() > 0){
            //$data['hasil'] = $query;
            $data['query'] = $this->surat_model->getSuratByCategory($cat, $page, $config['per_page']);
        } else {
            $data['message'] = 'Tidak ada data tersimpan pada kategori ini.';
        }
		
        $data['title'] = 'Surat';
        $this->load->view('show_surat_view', $data);
    }

    public function view($id) {
        $query = $this->surat_model->getSuratByID($id);
        $data['breadcrumb'] = $this->surat_model->getCategoriesById($id);
        // menentukan hasil query ada atau tidak
        if ($query['row'] > 0) {
            $data['hasil'] = $query['hasil'];
        } else {
            show_404();
            //$data['message'] = 'Tidak ada data tersimpan';
        }
        
        // load view
        $data['title'] = 'Detail Surat';
        $this->load->view('single_surat_view', $data);
    }

    public function edit($id) {
		$role = $this->session->userdata('role');
		if($role != 3){ // role untuk admin & editor
			// query berdasar id surat
			$query = $this->surat_model->getSuratByID($id);
			$row= $query['hasil']->row_array();
			// dump hasil query ke dalam variabel
			$data['value'] = array(
				'idsurat' => $row['idsurat'],
				'nama_instansi' => $row['nama_instansi'],
				'tanggal_kerjasama' => $row['tanggal_kerjasama'],
				'masa_berlaku' => $row['masa_berlaku'],
				'kerjasama_mengenai' => $row['kerjasama_mengenai'],
				'kode_surat' => $row['kode_surat'],
				'deskripsi' => $row['deskripsi'],
				'unit_terkait' => $row['unit_terkait'],
				'implementasi' => $row['implementasi'],
				'scan_file' => $row['scan_file'],
				'kategori' => $row['kategori_idkategori'],
				'iduser' => $row['loginuser_idloginuser'],
				'nomer_surat' =>$row['nomersurat']
			);

			// kategori untuk breadcrumb
			$data['kategori_parent']= $this->kategori_array(0);
			// existing surat category
			$data['kategori_selected'] = $this->surat_model->getCategories($data['value']['kategori']);
			$data['subkategori_parent'] = $this->kategori_array($data['kategori_selected'][2]["id"]);
			$data['childkategori'] = $this->kategori_array($data['kategori_selected'][1]["id"]);
			$data['title'] = 'Form Edit Surat';
			//echo $row->idsurat;
			$this->load->view('insert_surat_view', $data);
		} else {
			$this->session->set_flashdata('message', 'Anda tidak memiliki kewenangan untuk mengakses halaman ini');
			redirect('error');
		}
    }
	
	public function update(){
		$id = $this->input->post('id');
		
		//get data from form
		$data['nomersurat'] = $this->input->post('nomer-surat');
		$data['nama_instansi'] = $this->input->post('nama-instansi');
		$data['tanggal_kerjasama'] = $this->input->post('tanggal-kerjasama');
		$data['masa_berlaku'] = $this->input->post('masa-berlaku');
		$data['kerjasama_mengenai'] = $this->input->post('kerjasama');
		$data['kode_surat'] = $this->input->post('kode-surat');
		$data['deskripsi'] = $this->input->post('deskripsi');
		$data['unit_terkait'] = $this->input->post('unit-terkait');
		$data['implementasi'] = $this->input->post('implementasi');
		$data['kategori_idkategori'] = $this->input->post('kategori');
		$data['loginuser_idloginuser'] = $this->session->userdata('id');
		
		// field upload file name in form = file
		$filepath = 'file';
		
        //upload configuration
        $config['upload_path'] = './uploads/';
        $config['max_size'] = '0';
        $config['allowed_types'] = '*';
		
		//renaming file
		$filename = $_FILES[$filepath]['name'];
		$ext = pathinfo($filename, PATHINFO_EXTENSION);
		$this->load->helper('date');
		$config['file_name'] = now()."_".$data['kategori_idkategori']."_".$data['kode_surat']."_".$data['nomersurat'].".".$ext;
		
		// load library with configuration
		$this->load->library('upload', $config);
		
        if (!$this->upload->do_upload($filepath) == TRUE) {
			$this->surat_model->edit_surat($id, $data);
			
			$logdata['id_user'] = $this->session->userdata('id');
			$logdata['id_entitas'] = $id;
			$logdata['nama_tabel'] = 'surat';
			$logdata['action'] = 'edit';
			$this->log_model->setLogData($logdata);
			$this->session->set_flashdata('message', 'Surat <strong>'.$data['kode_surat'].'</strong> berhasil di update!');
            redirect('surat');
        } else {
            $upload_data = $this->upload->data('file_name');
            $data['scan_file'] = $upload_data['file_name'];
            $this->surat_model->edit_surat($id, $data);
			
			$logdata['id_user'] = $this->session->userdata('id');
			$logdata['id_entitas'] = $id;
			$logdata['nama_tabel'] = 'surat';
			$logdata['action'] = 'edit';
			$this->log_model->setLogData($logdata);
			$this->session->set_flashdata('message', 'Surat <strong>'.$data['kode_surat'].'</strong> berhasil di update!');
            redirect('surat');
        }
	}
    
	/** fungsi untuk mendapatkan kategori
	 *	parameter $id
	 *  return json
	 */
	public function get_kategori($id=0){
		$query = $this->surat_model->getCategoriesByParent($id); 
		$json = "";
		$arraydata = array();
		
		if ($query->num_rows() > 0) {
			foreach($query->result() as $row) {
				$data = array(
					'id' => $row->idkategori,
					'nama' => $row->nama_kategori
				);
				array_push($arraydata, $data);
			}
			$jsonarray = array("kategori"=>$arraydata);
			$json = json_encode($jsonarray);
		} else{
			$json = '{ "kategori": [{"-1":"Tidak ada data"}]';
		}
	
		$this->output
			 ->set_content_type('application/json')
			 ->set_output($json);
	}

	public function viewsearch(){
		$data['title'] = 'Hasil Pencarian';
		$this->load->view('hasil_pencarian', $data);
	}
	
	public function download ($filepath =""){
		$this->load->helper('download');
		$data = file_get_contents ('./uploads/'.$filepath);
		force_download($filepath,$data);
	}
}
?>
